<script setup lang="ts">
import type { ScrollbarInstance } from 'element-plus'
import { onMounted, ref } from 'vue'
import type { ScrollEvent } from './type'
const props = defineProps({
  downDistance: {
    type: Number,
    default: 20
  },
  scrollDelay: {
    type: Number,
    default: 100
  },
  immediately: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits<{
  (e: 'scrollDown'): void
  (e: 'scroll', event: ScrollEvent): void
}>()

// 定时器
let timeout = 0
// 滚动事件
const scrollBarRef = ref<ScrollbarInstance>()
let lastTop = 0
function onScroll(data: ScrollEvent) {
  emit('scroll', data)

  if (scrollBarRef.value?.wrapRef) {
    let ch = scrollBarRef.value.wrapRef.clientHeight
    let sh = scrollBarRef.value.wrapRef.scrollHeight
    if (data.scrollTop - lastTop < 0) {
      return
    }
    if (sh - ch - props.downDistance < data.scrollTop) {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        emit('scrollDown')
      }, props.scrollDelay)
    }
  }
  lastTop = data.scrollTop
}

// 加载
onMounted(() => {
  if (props.immediately) {
    scrollBarRef.value?.handleScroll()
  }
})
</script>
<template>
  <el-scrollbar @scroll="onScroll" ref="scrollBarRef">
    <slot></slot>
  </el-scrollbar>
</template>
<style scoped lang="less"></style>
